﻿var wechat=require('wechat');
var util=require('../base/Util');
var express = require('express');
var	router = express.Router();
var wechate = require('wechat-enterprise');

//数据库操作对象
var DbOpt = require("../models/Dbopt");
var WeixinShow= require("../models/WeixinShow");
var WeixinOrder= require("../models/WeixinOrder");
var WeixinUser= require("../models/WeixinUser");
var WeixinPCache= require("../models/WeixinPCache");

//配置文件
var settings = require("../models/db/settings");
var config = settings.wxconfig;
var enterpriseConfg=settings.enterpriseConfg;

var updatePCache=function(id,data,stepid,pid,fun){
	var conditions={},updateData={};
	conditions["wxid"]=id;
	updateData["data"]=data;
	if(stepid!=null&&stepid>0){
		updateData["stepid"]=stepid;
	}
	if(pid!=null&&pid>0){
		updateData["pid"]=pid;
	}
	DbOpt.update(WeixinPCache,conditions,updateData,function(){
		fun();
	});
}



var regProcess=function(wexinPcache,msg,res){
	var data=JSON.parse(wexinPcache.data);
	if(wexinPcache.stepid==1){//记录名字
		var reMsg= "请输入您的号码";
		data["name"]=msg;
		updatePCache(wexinPcache.wxid,JSON.stringify(data),2,2,function(){
			res.reply({ type: "text", content: reMsg});
		});
	}else if(wexinPcache.stepid==2){//记录号码
		data["phone"]=msg;
		updatePCache(wexinPcache.wxid,JSON.stringify(data),3,2,function(){
			var reMsg= "请输入地址";
			res.reply({ type: "text", content:reMsg});
		});
	}else if(wexinPcache.stepid==3){//记录地址

		data["address"]=msg;
		updatePCache(wexinPcache.wxid,JSON.stringify(data),4,2,function(){
			var reMsg= ">请确认您的个人信息  \n  名字： ["+data["name"]+"] \n  号码： ["+data["phone"]+"] \n  地址： ["+msg+"]\n1-确认信息 \n2-重新输入";
			res.reply({ type: "text", content:reMsg});
		});
	}else if(wexinPcache.stepid==4){//保存个人信息
		if(msg=="2"){
			var reMsg= "请输入您的名称";
			updatePCache(wexinPcache.wxid,JSON.stringify(data),1,2,function(){
				res.reply({ type: "text", content:reMsg});
			});
		}else{
			updatePCache(wexinPcache.wxid,JSON.stringify(data),1,1,function(){
				var addData={};
				addData["wxid"]=wexinPcache.wxid;
				addData["name"]=data["name"];
				addData["phone"]=data["phone"];
				addData["address"]=data["address"];
				DbOpt.addOne(WeixinUser,addData,function(){
					if(data["cachemsg"]!=null&&data["cachemsg"]!=""){
						doOrder(wexinPcache,data,data["cachemsg"],res)
					}else{
						var reMsg= "您的信息已保存!";
						res.reply({ type: "text", content:reMsg});
					}
				});

			});
		}
	}
}

/*
 * 下订单
 */
var doOrder=function(wexinPcache,data,msg,res){
	// 如果基本资料其中一项为空则强制填写
	if(util.ds(data["name"])==""||util.ds(data["phone"])==""||util.ds(data["address"])==""){
		data["cachemsg"]=msg;
		updatePCache(wexinPcache.wxid,JSON.stringify(data),1,2,function(){
			reMsg=" 请输入您的名称";
			res.reply({ type: "text", content: reMsg});
		});
		return;
	}
	var orderData=[];
	var reMsg="";
	//先截取留言部分
	var lmsg="";
	var tmp=msg.split("\n");
	lmsg=tmp.lenth>1?tmp[1]:"";
	console.log(tmp);
	if(tmp.length>1){
		lmsg=tmp[1];
		msg=tmp[0];
	}

	msg=msg.substring(1);
	var csmsg="";
	var errorMsg="";
	var BSON = require('mongodb');
	var menuCache=data["menucache"];
	var orderGroups=msg.split(" ");
	for(var i=0;i<orderGroups.length;i++){
		var nameStr="";
		var orderItemData={};
		var csGroups=orderGroups[i].split("#");
		var count=1;
		csmsg=csmsg+(i+1)+". ";
		for(var j=0;j<csGroups.length;j++){
			var countFlag=csGroups[j].indexOf("*");
			if(countFlag>0){
				count=csGroups[j].substring(countFlag+1);
				csGroups[j]=csGroups[j].substring(0,countFlag);
			}
			var menuinfo=menuCache[csGroups[j]];
			nameStr+= (menuinfo!=null?menuinfo.name+" ":"");
			csmsg+=(menuinfo!=null?  (j!=0?"    ":"")+menuinfo.name+"\n":"");
		}
		csmsg+=" > x "+count+"份 \n";
		orderItemData["name"]=nameStr;
		orderItemData["count"]=count;
		orderData.push(orderItemData);
	}
	data["orderInfo"]=orderData;
	data["orderMsg"]=lmsg;
	updatePCache(wexinPcache.wxid,JSON.stringify(data),2,1,function(){
		var infomsg=  "  名字： ["+data["name"]+"] \n  号码： ["+data["phone"]+"] \n  地址： ["+data["address"]+"] ";
		reMsg=" >  您的订单如下\n"+csmsg+"\n"+
			" >  您的送货信息如下\n"+infomsg+
			" \n{留言内容 :" +lmsg+"}\n\n"+
			"   1-确认订单\n   2-取消订单\n   3-修改名称\n   4-修改号码 \n   5-修改地址\n   6-修改留言";
		res.reply({ type: "text", content: reMsg});
	});
}


/*
 * 展示菜单
 */
var showMenu=function(wexinPcache,data,msg,res){
	var queryCondition={};
	var week=new Date().getDay();
	week=week==0?week=7:week;
	queryCondition["week"]=week;
	queryCondition["dis"]=1;
	DbOpt.pagination(WeixinShow,queryCondition,1,999,function(qinfo){
		var weixinshows=qinfo.docs;
		var reMsg="";
		var rMsg="";
		var cMsg="";
		var rcount=1;
		var menuCache={};
		for(var i=0;i<weixinshows.length;i++){
			if(weixinshows[i].cstype==1){
				menuCache[""+rcount]=weixinshows[i];
				rMsg+=rcount+"."+weixinshows[i].name+" ";
				rcount++;
			}
		}

		for(var i=0;i<weixinshows.length;i++){
			if(weixinshows[i].cstype==2){
				menuCache[""+rcount]=weixinshows[i];
				cMsg+=rcount+" "+weixinshows[i].name+" ";
				rcount++;
			}
		}
		data["menucache"]=menuCache;
		updatePCache(wexinPcache.wxid,JSON.stringify(data),1,1,function(){
			reMsg="外卖热线：0760-23619536。\n肉类:\n"+rMsg+" \n\n菜类:\n"+cMsg+"\n \n A-进入网页订购\n B-命令订购模式帮助";
			res.reply({ type: "text", content: reMsg});
		});
	});
}

var msgToAll=function(msg){
	var to={'touser':'@all'};
	var message={ "msgtype": "text","text": {
		"content": msg
	}};
	var api = new wechate.API(enterpriseConfg.corpId, enterpriseConfg.secret, enterpriseConfg.agentid);
	api.send(to,message, function (err, data, rest) {
		console.log("已发送全体信息!");
	});
}

var confirmOrder=function(wexinPcache,msg,res){
	var data=JSON.parse(wexinPcache.data);
	var addData={};
	var orderMsg=data["orderMsg"];
	var orderData=data["orderInfo"];
	addData["wxid"]=wexinPcache.wxid;
	addData["name"]=data["name"];
	addData["phone"]=data["phone"];
	addData["address"]=data["address"];
	addData["status"]=0;
	addData["items"]=orderData;
	addData["remark"]=orderMsg;
	DbOpt.addOne(WeixinOrder,addData,function(){
		updatePCache(wexinPcache.wxid,JSON.stringify(data),1,1,function(){
			var reMsg="";
			reMsg="您已确认订单成功！";
			var bMsg="您有新的订单请注意处理\n";
			for(var i=0;i<orderData.length;i++){
				bMsg+=(i+1)+"."+orderData[i].name+" x"+orderData[i].count+"份\n";
			}
			bMsg+="\n送货信息:\n"
			bMsg+="名称:"+data["name"]+"\n"	;
			bMsg+="号码:"+data["phone"]+"\n"	;
			bMsg+="地址:"+data["address"]+"\n";
			bMsg+="留言内容:"+orderMsg+"\n";
			bMsg+=" > "+	new Date().toLocaleDateString()+" "+new Date().toLocaleTimeString();
			msgToAll(bMsg);
			res.reply({ type: "text", content: reMsg});
		});
	});
}




var defaultProcess=function(wexinPcache,msg,res){
	var data=JSON.parse(wexinPcache.data);

	if(wexinPcache.stepid==1){//主菜单列表
		var reg=new RegExp("^\\+");
		if(reg.test(msg)){//下订单
			doOrder(wexinPcache,data,msg,res);
		}else if(msg=="a"||msg=="A"){
			res.reply({ type: "text", content: "请点击以下链接进入订购:\nhttp://112.74.74.142/order/init?wxid="+wexinPcache.wxid});
		}else if(msg=="b"||msg=="B"){
			res.reply({ type: "text", content: "快捷订购格式:\n\n+4#5#2*2 4#1#2\n这里填写留言内容什么的\n\n+4#5#2代表菜式前面的编号用#分隔,*2表示2份,多份不同的用空格隔开,消息回车后可输入留言内容"});
		}else{//展示菜单
			showMenu(wexinPcache,data,msg,res);
		}
	}else if(wexinPcache.stepid==2){
		if(msg=="1"){//确认订单
			confirmOrder(wexinPcache,msg,res);
		}else if(msg=="2"){//返回主界面
			showMenu(wexinPcache,data,msg,res);
		}else if(msg=="3"){//修改名称
			updatePCache(wexinPcache.wxid,JSON.stringify(data),1,3,function(){
				var reMsg=" 请输入您的名称";
				res.reply({ type: "text", content: reMsg});
			});
		}else if(msg=="4"){//修改号码
			updatePCache(wexinPcache.wxid,JSON.stringify(data),2,3,function(){
				var reMsg=" 请输入您的号码";
				res.reply({ type: "text", content: reMsg});
			});
		}else if(msg=="5"){//修改地址
			updatePCache(wexinPcache.wxid,JSON.stringify(data),3,3,function(){
				var reMsg=" 请输入您的地址";
				res.reply({ type: "text", content: reMsg});
			});
		}else if(msg=="6"){//修改留言
			updatePCache(wexinPcache.wxid,JSON.stringify(data),4,3,function(){
				var reMsg=" 请输入您的留言";
				res.reply({ type: "text", content: reMsg});
			});
		} else{
			showMenu(wexinPcache,data,msg,res);
		}
	}
}

/*
 * 修改个人资料
 */
var mdfInfo=function(wexinPcache,msg,res){
	var data=JSON.parse(wexinPcache.data);
	console.log(data);
	if(wexinPcache.stepid==1)
		data["name"]=msg;
	else if(wexinPcache.stepid==2)
		data["phone"]=msg;
	else if(wexinPcache.stepid==3)
		data["address"]=msg;
	else if(wexinPcache.stepid==4)
		data["orderMsg"]=msg;
	updatePCache(wexinPcache.wxid,JSON.stringify(data),1,2,function(){
		doOrder(wexinPcache,data,data["cachemsg"],res);
	});
}




var talkProcess=function(wxid,msg,res){
	var queryCondition={};
	queryCondition["wxid"]=wxid;
	DbOpt.pagination(WeixinPCache,queryCondition,1,999,function(qinfo){
		var wexinPcaches=qinfo.docs;
		if(wexinPcaches.length>0){
			if(wexinPcaches[0].pid==1){//默认处理流程
				defaultProcess(wexinPcaches[0],msg,res);
			}else if(wexinPcaches[0].pid==2){//注册流程
				regProcess(wexinPcaches[0],msg,res);
			}else if(wexinPcaches[0].pid==3){//修改个人资料相关
				mdfInfo(wexinPcaches[0],msg,res);
			}
		}else{
			var addData={};
			addData["wxid"]=wxid;
			addData["stepid"]=1;
			addData["pid"]=1;
			addData["data"]="{}";
			var wexinPcache={};
			wexinPcache.data="{}";
			wexinPcache.stepid=1;
			wexinPcache.pid=1;
			wexinPcache.wxid=wxid;
			DbOpt.addOne(WeixinPCache,wexinPcache,function(){
				defaultProcess(wexinPcache,msg,res);
			})
		}
	})
}


router.post('/wechat', wechat(config, function (req, res, next) {
	var api = new wechate.API(enterpriseConfg.corpId, enterpriseConfg.secret, enterpriseConfg.agentid);

	var message = req.weixin;
	if(message.MsgType == 'text'){
		talkProcess(message.FromUserName,message.Content,res);
//    	var to={'touser':'lyw'};
//    	var message={ "msgtype": "text","text": {
//    	       "content": "Holiday Request For Pony(http://xxxxx)"
//    	   }};
//    	api.send(to,message, function (err, data, rest) {
//    		console.log(data);
//    		 var text="name:"+message.FromUserName+" content:"+message.Content;
//    		 
//    		 var queryCondition={};
//    		 	var week=new Date().getDay();
//				week=week==0?week=7:week;
//    			queryCondition["week"]=week;
//    			queryCondition["dis"]=1;
//    			WeixinShowDao.list(queryCondition,1,999,function(weixinshows) {
//    				var reMsg="";
//    				var rMsg="";
//    				var cMsg="";
//    				for(var i=0;i<weixinshows.length;i++){
//    					if(weixinshows[i].cstype==1){
//    						rMsg+=weixinshows[i].name+" ";
//    					}else{
//    						cMsg+=weixinshows[i].name+" ";
//    					}
//    				}
//    				reMsg="肉类:"+rMsg+" 菜类:"+cMsg;
//    				res.reply({ type: "text", content: reMsg});  
//    			});


		// response
//    		});

	}
}));

router.get('/corp', wechate(enterpriseConfg, function (req, res, next) {
	var message = req.weixin;
	console.log(message);
	var text="name:"+message.FromUserName+" content:"+message.Content;
//	  res.reply({ type: "text", content: text});
}));

router.post('/corp', wechate(enterpriseConfg, function (req, res, next) {
	var message = req.weixin;
	console.log(message);
	var text="name:"+message.FromUserName+" content:"+message.Content;
//	  res.reply({ type: "text", content: text});
}));


module.exports = router;